# encoding:utf-8
from flask import Flask, request
from unipath import Path
from loguru import logger
from typing import Optional
from functools import partial
import os

# 配置logger
logger.add("app.log", rotation="500 MB", level="INFO")

# Flask应用实例化
app = Flask(__name__)

# 常量配置
PATHS = {
    'EMBY_ROOT': 'E:/emby',
    'TARGET_ROOT': 'Y:/115',
    'POTPLAYER': 'D:/Program Files/DAUM/PotPlayer/PotPlayerMini64.exe'
}


def transform_path(file_path: str) -> Optional[Path]:
    """
    转换文件路径

    Args:
        file_path (str): 原始文件路径

    Returns:
        Optional[Path]: 转换后的路径对象
    """
    try:
        path = Path(file_path)
        if '艺术视频' in str(path):
            # 处理艺术视频路径
            new_path = Path(file_path.replace(r'E:\emby', r'Y:'))
            return Path(new_path.parent.parent, new_path.name)
        else:
            # 处理影视剧集路径
            return Path(file_path.replace(r'E:\emby', r'Y:\影视剧集'))
    except Exception as e:
        logger.error(f"路径转换失败: {e}")
        return None


def execute_potplayer(file_path: Path) -> bool:
    """
    启动PotPlayer播放视频

    Args:
        file_path (Path): 要播放的文件路径

    Returns:
        bool: 执行是否成功
    """
    try:
        # 设置控制台编码
        os.system('chcp 65001')
        cmd = f'"{PATHS["POTPLAYER"]}" "{file_path}"'
        logger.info(f"执行命令: {cmd}")
        os.popen(cmd)
        return True
    except Exception as e:
        logger.error(f"执行PotPlayer失败: {e}")
        return False


@app.route('/launched_potplayer', methods=["GET"])
def launched_potplayer():
    """处理PotPlayer启动请求"""
    file_path = request.args.get("file_path")

    if not file_path:
        logger.warning("请求中未包含文件路径")
        return "文件路径为空", 400

    logger.info(f"收到播放请求，原始路径: {file_path}")

    new_path = transform_path(file_path)
    if not new_path:
        return "路径转换失败", 500

    logger.info(f"转换后的路径: {new_path}")

    if execute_potplayer(new_path):
        return "命令执行成功", 200
    else:
        return "命令执行失败", 500


if __name__ == '__main__':
    logger.info("应用启动")
    app.run(debug=True)
